package res

import (
	"blog_go/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

type ListResponse[T any] struct {
	Count int64 `json:"count"`
	List  T     `json:"list"`
}

type ErrorMsg struct {
	Err  error
	Data any
}

const (
	Success = 0
	Error   = 7
)

func Result(code int, msg string, data any, c *gin.Context) {
	c.JSON(http.StatusOK, Response{
		code,
		msg,
		data,
	})
}

func Ok(msg string, data any, c *gin.Context) {
	Result(Success, msg, data, c)
}

func OkWithDate(data any, c *gin.Context) {
	Result(Success, "成功", data, c)
}

func OkWithMessage(msg string, c *gin.Context) {
	Result(Success, msg, true, c)
}

func OkWithList(list any, count int64, c *gin.Context) {
	Result(Success, "成功", ListResponse[any]{
		Count: count,
		List:  list,
	}, c)
}

func Fail(msg string, data any, c *gin.Context) {
	Result(Error, msg, data, c)
}

func FailWithMessage(msg string, c *gin.Context) {
	Result(Error, msg, false, c)
}

func FailWithCode(code ErrorCode, c *gin.Context) {
	msg, ok := ErrorMap[code]
	if ok {
		Result(int(code), msg, false, c)
		return
	}
	Result(Error, "未知错误", false, c)
}

func FailWithError(err error, data any, c *gin.Context) {
	Result(Error, utils.GetValidMsg(err, data), false, c)
}
